package org.misty.redis.web.config;

import org.misty.redis.client.JedisPoolAdapter;
import org.misty.redis.client.RedisTemplateAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.JedisPool;

import java.lang.reflect.Field;

/**
 * @author Misty on 2020-06-01
 */
@Configuration
public class ClientConfigurer {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> rt = new RedisTemplate<>();
        rt.setConnectionFactory(factory);
        rt.setKeySerializer(RedisSerializer.string());
        rt.setValueSerializer(RedisSerializer.java());
        rt.afterPropertiesSet();
        return rt;
    }

    @Bean
    public JedisPool jedisPool(JedisConnectionFactory factory) throws Exception {
        Field f = JedisConnectionFactory.class.getDeclaredField("pool");
        f.setAccessible(true);
        return (JedisPool) f.get(factory);
    }

    @Bean
    public RedisTemplateAdapter redisTemplateAdapter(StringRedisTemplate redisTemplate) {
        return new RedisTemplateAdapter(redisTemplate);
    }

    @Bean
    public JedisPoolAdapter jedisPoolAdapter(JedisPool jedisPool) {
        return new JedisPoolAdapter(jedisPool);
    }
}
